//
//  AddPlanViewModel.m
//  LittleFairyPoet
//
//  Created by rimi on 15/9/10.
//  Copyright (c) 2015年 周林. All rights reserved.
//

#import "WPAddPlanViewModel.h"
#import "WPAlerView.h"

@implementation WPAddPlanViewModel
+(void)saveNewPlanWithPlan:(Plan *)model andWithReturnFlag:(void (^)(NSInteger))complete {
    if (model.planTime.length== 0 |model.createTime.length == 0| model.peoms.count == 0) {
        [WPAlerView showAlertViewWithMsg:@"请完整计划"];
        return;
    }
    NSFileManager * manager = [NSFileManager defaultManager];
    
    NSArray * array = [NSArray arrayWithObjects:model.planTime, [NSString stringWithFormat:@"创建于%@",model.createTime], model.peoms, model.topTime, @(model.topOn), nil];
    NSMutableArray * existPlan = nil;
    if (![manager fileExistsAtPath:[self plistPath]]) {
        existPlan = [NSMutableArray arrayWithObject:array];
    } else {
        existPlan = [NSMutableArray arrayWithContentsOfFile:[self plistPath]];
        BOOL isExist = NO;
        for (int i = 0; i < existPlan.count; i++) {
            if ([existPlan[i][0] isEqualToString:array[0]]) {
                [existPlan replaceObjectAtIndex:i withObject:array];
                isExist = YES;
            }
        }
        if (!isExist) {
            [existPlan addObject:array];
        }
    }
    if ([existPlan writeToFile:[self plistPath] atomically:YES]) {
        complete(0);
    } else {
        complete(1);
    }
}
+ (void)replacePlanWithPlan:(Plan *)plan {
    NSMutableArray * existPlan = [self readPlan];
    NSArray * array = [NSArray arrayWithObjects:plan.planTime, [NSString stringWithFormat:@"创建于%@",plan.createTime], plan.peoms, nil];
    for (int i = 0; i < existPlan.count; i++) {
        if ([existPlan[i][0] isEqualToString:array[0]]) {
            [existPlan replaceObjectAtIndex:i withObject:array];
        }
    }
}
+ (NSMutableArray *)readPlan {
  NSMutableArray * existPlan = [NSMutableArray arrayWithContentsOfFile:[self plistPath]];
    return existPlan;
}
+ (void)deleteSignalPlanWithPlanTime:(NSString *)planTime {
    NSMutableArray * existPlan =[self readPlan];
    for (int i = 0; i < existPlan.count; i++) {
        if ([existPlan[i][0] isEqualToString:planTime]) {
            [existPlan removeObjectAtIndex:i];
        }
    }
    [existPlan writeToFile:[self plistPath] atomically:YES];
    [WPAlerView showAlertViewWithMsg:@"删除成功"];
}
+ (void)deleteAllPlan {
    NSFileManager * manager = [NSFileManager defaultManager];
    if ([manager removeItemAtPath:[self plistPath] error:nil]) {
        [WPAlerView showAlertViewWithMsg:@"删除成功"];
    }
}
+ (NSString *)plistPath {
    NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString *path = [paths objectAtIndex:0];
    NSString * plistPath = [path stringByAppendingString:@"/plan.plist"];
    return plistPath;
}
@end
